package itcz.example.pattern.create_action.factory.config_factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

/**
 * @ClassName: CoffeeFactory
 * @Author: ITCZ
 * @Date: 2025-05-02
 * @Description:
 */
public class CoffeeFactory {

    //1.定义容器对象存储咖啡对象
    private static HashMap<String, Coffee> map = new HashMap<>();

    //2.加载配置文件
    static {
        // 2.1.创建Properties
        Properties properties = new Properties();
        // 2.2 调用p对象的load方法，加载配置文件
        InputStream is = CoffeeFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        try {
            properties.load(is);
            Set<Object> keySet = properties.keySet();
            for (Object key : keySet) {
                String className = properties.getProperty((String) key);
                // 通过反射创建对象
                Class clazz = Class.forName(className);
                Coffee coffee = (Coffee) clazz.newInstance();
                map.put((String) key, coffee);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Coffee createCoffee(String type) {
        return map.get(type);
    }
}
